<template>
  <div class="relative inline-block">
    <div
      class="flex items-center justify-between w-[{{ width }}px] px-2 py-1 text-xs text-gray-300 border border-gray-600 rounded cursor-pointer hover:border-blue-500"
      @click.stop="isOpen = !isOpen"
    >
      <span class="">{{ selected?.label || '请选择' }}</span>
      <span class="ml-2">▼</span>
    </div>

    <div
      v-if="isOpen"
      class="scrollbar-small absolute max-h-[300px] overflow-y-auto z-10 w-[{{ width }}px] mt-1 bg-gray-800 border border-gray-500 rounded shadow-lg"
    >
      <div
        v-for="option in options"
        :key="option.value"
        class="px-2 py-1 text-xs text-gray-300 hover:bg-blue-500 hover:text-white cursor-pointer"
        @click="selectOption(option)"
      >
        {{ option.label }}
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref, watch, onMounted, onUnmounted } from 'vue'

const props = withDefaults(
  defineProps<{
    options: Array<{
      label: string
      value: string | number
    }>
    modelValue: string | number
    width?: string
  }>(),
  {
    width: '30',
  },
)

const emit = defineEmits(['update:modelValue'])

const isOpen = ref(false)
const selected = ref<{ label: string; value: string | number } | null>(null)

// 监听modelValue变化,更新selected
watch(
  () => props.modelValue,
  (newVal) => {
    const option = props.options.find((opt) => opt.value === newVal)
    if (option) {
      selected.value = option
    }
  },
  { immediate: true },
)

const selectOption = (option: { label: string; value: string | number }) => {
  selected.value = option
  isOpen.value = false
  emit('update:modelValue', option.value)
  emit('change', option.value)
}

// 点击外部关闭下拉框
const handleClickOutside = (event: MouseEvent) => {
  const target = event.target as HTMLElement
  if (!target.closest('.relative')) {
    isOpen.value = false
  }
}

onMounted(() => {
  document.addEventListener('click', handleClickOutside)
})

onUnmounted(() => {
  document.removeEventListener('click', handleClickOutside)
})
</script>

<style scoped>
.scrollbar-small::-webkit-scrollbar {
  width: 4px;
  height: 4px;
}

.scrollbar-small::-webkit-scrollbar-track {
  @apply bg-gray-700 bg-opacity-40;
  border-radius: 2px;
}

.scrollbar-small::-webkit-scrollbar-thumb {
  @apply bg-gray-500;
  border-radius: 2px;
}

.scrollbar-small::-webkit-scrollbar-thumb:hover {
  @apply bg-gray-400;
}

/* 兼容 Firefox */
@supports (scrollbar-width: thin) {
  .scrollbar-small {
    scrollbar-width: thin;
    scrollbar-color: #6b7280 #374151;
  }
}
</style>
